package com.jiuzhe.commercial.ui.components;

import android.R.color;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.bean.HotelstateBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * this class is used for draw report table, which contains layer A, B, C, and D.
 * last view, D, designed to show reminder views. these views can be used for refreshment or
 * giving messages to users in friendly way.
 * layer A is in first row of report table head.
 * layer B is in second row of report table head, which lays below layer A
 * layer C is filled with data content below layer B in report table head.
 * layer D is under layer C
 *
 * @author yishaqi
 */
public class EQComplexTable extends TableBaseObj implements EQCustomListViewListener, EQGridCtrl.EQGridCtrlDataSource {

    private List<HashMap<String, String>> fixdata = new ArrayList<>();
    private List<HashMap<String, Object>> otherdata = new ArrayList<>();
    public String TAG = "EQComplexTable";
    //	public static final float tableHeight = 739;						//	table height need to be altered
//	public static final float titleCellHeight = 33;						//	table content height of unit text view
//	public static final float secondTitleCellHeight = 66;				//	second title height
    public static final LinearLayout.LayoutParams WRAP_CONTENT = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);                                    //	WRAP_CONTENT
    public static final LinearLayout.LayoutParams MATCH_PARENT = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    public static final int BACKGROUNDblack = color.black;
    public static final int BACKGROUNDBLACK = Color.BLACK;
    public static final int BACKGROUNDCOLOR = 00000000;
    public static final int firstHeaderBackgroundColor = 0x0f000000;    //	first level Header Background Color
    public static final int frozenColumnsBackgroundColor = 0x2f000000;    //	frozen Columns Background Color
    public static final int displayRows = 10;                            //	max rows display in one screen
    public static final int requestRows = 15;                            //	request rows once request
    public static final int testColorDown = Color.YELLOW;                //	used for testing click event
    public static final int testColorUp = Color.RED;                    //	used for testing click event
    public static final int testColorNormal = Color.CYAN;                //	used for testing click event
    public static final String blankValue = "";                            //	blank value
    public static final int BACKGROUNDDeepBlack = 0xFF272625;
    public static final int textColorNormal = 0xffaeaeae;
    public static final int textColorVariationalContent = 0xff666666;

    public static final int OVER_SCROLL_ALWAYS = 0;
    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
    public static final int OVER_SCROLL_NEVER = 2;

    private int idsCount = 0;

    /**
     * common density:	480 * 800
     * density value: 240
     */
    @SuppressWarnings("unused")
    private int commonDensity = 240;

    /**
     * text Size in pxValue
     */
    private int textSizeBig = 12;
    /**
     * table height
     */
    private float tableHeight = 0;

    /**
     * second title cell height
     */
    private float secondTitleCellHeight = 60;

    /**
     * title content cell height
     */
    private float tableContentCellHeight = 0;

    /**
     * record table header depth
     */
    private int headerDepth = 2;

    /**
     * request Page Index
     */
    private int requestPageIndex = 1;

    /**
     * record the click title's column index
     * o~columns's length
     */
//	private String mTableOrderIndex = null;

    /**
     * record the sorting style of table
     * -1 is the default value
     * 0 is the descend value
     * 1 is the ascend value
     */
    private int mTableOrderStyle = -1;

    /**
     * record the sort-able of table
     */
    private boolean orderable = true;

    /**
     * the value of frozen columns  is 1 for the time being
     * mFrozenTitles.length
     */
    private int mFrozenColumns;

    /**
     * record rows count of table content
     */
    private int currentRowsCount = 0;

    /**
     * record rows count before loading more
     */
    private int lastRowsCount = 0;

    /**
     * record real add rows count of table content
     */
    private int addRows = 0;

    //    /**
//     * report Table View
//     */
//    private View reportTableView;
    private EQGridCtrl mGridCtrl;

    private List<HotelstateBean.HeadBean> head;
    private List<List<HotelstateBean.BodyBean>> bodyData;
    private List<HotelstateBean.LeftBean> left;
    private ArrayList<String> leftBodyData = new ArrayList<>(requestRows);
    private HashMap<String, ArrayList<HotelstateBean.BodyBean>> rightBodyData = new HashMap<>();

    public ViewGroup getEQRootView() {
        return rootView;
    }

    public void setEQRootView(ViewGroup rootView) {
        this.rootView = rootView;
    }

    private ViewGroup rootView;

    /**
     * left header
     */
//	private LinearLayout leftHead;

    /**
     * layer C，表内容数据层
     * left frozen column
     * maybe one column or two columns
     */
//	private EQCustomListView leftLst;

    /**
     * layer A, B, C, 表固定列
     * left linear layout
     */
//	private LinearLayout leftLly;
    private int leftViewWidth = 0;

    /**
     * layer A, B, C, 表左右可滑动区
     * right scroll view
     */
//	private HorizontalScrollView rightHsv;

    /**
     * layer A, B, C, 表左右滑动区的内容
     * right linear layout
     */
//	private LinearLayout rightLly;

    /**
     * C 层，表内容数据层
     * variational columns
     */
//	private EQCustomListView rightLst;

    /**
     * A 层，表头第一行
     * first header
     * variational titles
     */
    private ArrayList<ReportTitleStruct> mVariationalTITLES = new ArrayList<ReportTitleStruct>(40);

    /**
     * B 层，表头第二行
     * second header
     */
    private ArrayList<ReportTitleStruct> variationalTitlesChildren = new ArrayList<ReportTitleStruct>(40);

    /**
     * A 层，表头第一行
     * first header
     * frozen titles
     */
    private ArrayList<ReportTitleStruct> mFrozenTITLES = new ArrayList<ReportTitleStruct>(10);

    /**
     * B 层，表头第二行
     * second header
     * frozen second titles
     */
    private ArrayList<ReportTitleStruct> frozenTitlesChildren = new ArrayList<ReportTitleStruct>(10);

    /**
     * record left frozen data
     */
    private ArrayList<HashMap<String, String>> recordLeftFrozenData = new ArrayList<HashMap<String, String>>(60);

    /**
     * record right Variational Data
     */
    private ArrayList<HashMap<String, Object>> recordRightVariationalData = new ArrayList<>(60);

    /**
     * last level Frozen Titles
     */
    private ArrayList<ReportTitleStruct> lastLevelFrozenTitles = new ArrayList<ReportTitleStruct>(10);

    /**
     * last level variational Titles
     */
    private ArrayList<ReportTitleStruct> lastLevelVariationalTitles = new ArrayList<ReportTitleStruct>(40);

    /**
     * save sort states in table head
     */
    private HashMap<String, String> sortParam = new HashMap<String, String>();

    /**
     * to compute add rows
     */
    private ArrayList<String> temporaryData = new ArrayList<String>(requestRows);

    /**
     * all data are placed here
     */
    public HashMap<String, ArrayList<? extends Object>> tableData = new HashMap<>();

    private Handler mHandler = new Handler();
    private Context context;
    private String reportLayerName;
    private ReportTitleStruct reportTitleStruct;

    private boolean dialogShow = false;

    /**
     * 是当前页面，上拉刷新时候在表上添加数据，为FALSE时候要清掉表的数据，在填充数据
     */
    @SuppressWarnings("unused")
//    private boolean isCurrent;

    /**
     * construction function
     *
     * @param context
     * @param
     */
    public EQComplexTable(Context context) {
        super(context);
        this.context = getContext();
    }

    public EQGridCtrl getmGridCtrl() {
        return mGridCtrl;
    }

    public void setmGridCtrl(EQGridCtrl mGridCtrl) {
        this.mGridCtrl = mGridCtrl;
    }

    private ArrayList<String> getColumnIdLeft(String column_id){
        return leftBodyData;
    }

    private ArrayList<HotelstateBean.BodyBean> getColumnIdRight(String column_id){
        ArrayList<HotelstateBean.BodyBean> data = new ArrayList<>();
        ArrayList<HotelstateBean.BodyBean> bodyBeans = rightBodyData.get(column_id);
        int size = bodyBeans.size();
        for (int i = 0; i < size; i++) {
            data.add(bodyBeans.get(i));
        }

        return data;
    }

    private void composeLeftBodyData(){
        for (int i = 0; i < left.size(); i++) {
            leftBodyData.add(left.get(i).getSkuName());
        }
    }

    private void composeRightBodyData(){
        int length = lastLevelVariationalTitles.size();
        for (int i = 0; i < length; i++) {
            rightBodyData.put(lastLevelVariationalTitles.get(i).getmTitleName(), new ArrayList<HotelstateBean.BodyBean>(requestRows));
        }
        int lines = bodyData.size();
        for (int line = 0; line < lines; line++) {
            List<HotelstateBean.BodyBean> lineBodyBeans = bodyData.get(line);
            int size = lineBodyBeans.size();
            for (int column = 0, beanIndex = 0; column < length; column++) {
                HotelstateBean.BodyBean bodyBean = null;
                String headDate = head.get(column).getDate();
                if (beanIndex < size && headDate.equals(lineBodyBeans.get(beanIndex).getDate())) {
                    bodyBean = lineBodyBeans.get(beanIndex);
                    beanIndex ++;
                } else {
                    bodyBean = new HotelstateBean.BodyBean(headDate);
                }
                rightBodyData.get(lastLevelVariationalTitles.get(column).getmTitleName()).add(bodyBean);
            }
        }
    }

    public void produceTableData(){
        temporaryData.clear();
        rightBodyData.clear();
        leftBodyData.clear();
        tableData.clear();

        composeLeftBodyData();
        composeRightBodyData();

        int lastLevelFrozenSize = lastLevelFrozenTitles.size();
        /*	request data need to implement relevant interface	*/
        for (int i = 0; i < lastLevelFrozenSize; i++) {
            tableData.put(lastLevelFrozenTitles.get(i).getmTitleName(), getColumnIdLeft(lastLevelFrozenTitles.get(i).getmTitleName()));
            Log.i(TAG, "请求固定列id:" + lastLevelFrozenTitles.get(i).getmTitleName());
            if (i == 0) {
                temporaryData = getColumnIdLeft(lastLevelFrozenTitles.get(i).getmTitleName());
                temporaryData.trimToSize();
            }
        }

        int lastLevelVariationalSize = lastLevelVariationalTitles.size();
        for (int i = 0; i < lastLevelVariationalSize; i++) {
            tableData.put(lastLevelVariationalTitles.get(i).getmTitleName(), getColumnIdRight(lastLevelVariationalTitles.get(i).getmTitleName()));
            Log.i(TAG, "请求非固定列id:" + lastLevelVariationalTitles.get(i).getmTitleName());
        }

        /*	compute addRows	*/
        if (temporaryData != null) {
            addRows = temporaryData.size();
            Log.i(TAG, "addRows :" + addRows);

            if (addRows < requestRows) {
                if (mGridCtrl != null) {
                    mGridCtrl.setPullLoadEnable(false);
                }
            }
        }
        currentRowsCount = currentRowsCount + addRows;
    }

    /**
     * after user pull to fresh table,
     * we write more receive data into tableData container
     * request table data
     */
    public void requestTableData() {

        temporaryData.clear();
        rightBodyData.clear();
        leftBodyData.clear();
        tableData.clear();

        /*	request data need to implement relevant interface	*/
        for (int i = 0; i < lastLevelFrozenTitles.size(); i++) {
            tableData.put(lastLevelFrozenTitles.get(i).getmTitleName(), eQTableOnListener.getColumnId(reportLayerName, lastLevelFrozenTitles.get(i).getmTitleName()));
            Log.i(TAG, "请求固定列id:" + lastLevelFrozenTitles.get(i).getmTitleName());
            if (i == 0) {
                temporaryData = eQTableOnListener.getColumnId(reportLayerName, lastLevelFrozenTitles.get(i).getmTitleName());
                temporaryData.trimToSize();
            }
        }

        for (int i = 0; i < lastLevelVariationalTitles.size(); i++) {
            tableData.put(lastLevelVariationalTitles.get(i).getmTitleName(), eQTableOnListener.getColumnId(reportLayerName, lastLevelVariationalTitles.get(i).getmTitleName()));
            Log.i(TAG, "请求非固定列id:" + lastLevelVariationalTitles.get(i).getmTitleName());
        }

        /*	compute addRows	*/
        if (temporaryData != null) {
            addRows = temporaryData.size();
            Log.i(TAG, "addRows :" + addRows);
            if (addRows < requestRows) {
                if (mGridCtrl != null) {
                    mGridCtrl.setPullLoadEnable(false);
                }
            }
        }
        currentRowsCount = currentRowsCount + addRows;
    }

    /**
     * refresh table after pulling down right list view
     *
     * @param
     */
    public void refreshTable() {

        //	fill table again as the first time
        if (mGridCtrl != null) {
            fixdata = getFrozenData();
            otherdata = getData();
            mGridCtrl.notifyDataSetChanged();
        }
        currentRowsCount = addRows;
    }

    /**
     * initialize complex table
     */
    public void initializeComplexTable() {
        startRefresh();
    }

    /**
     * add solid Data Content after pull up
     * solid data capacity added is x rows once
     */
    public void addDataContent(Context context) {
        if (mGridCtrl != null) {
            fixdata = getFrozenData();
            otherdata = getData();
            mGridCtrl.notifyDataSetChanged();
        }
    }

    /**
     * initialize table header without table content
     */
    public void initTableWithoutContent(Context context) {

        initializeComplexTable();
        if (mGridCtrl != null) {
            mGridCtrl.setPullLoadEnable(true);
        }
    }

    /**
     * initialize titles
     */
    private void initTitlesContent(ReportTitleStruct reportTitleStruct) {

        for (int i = 0, m = 0, n = 0; i < (reportTitleStruct.getmTitleChildren()).length; i++) {
            if (reportTitleStruct.getmTitleChildren() != null && reportTitleStruct.getmTitleChildren().length > 0) {
                if (reportTitleStruct.getmTitleChildren()[i] != null) {
                    if ("0".equals(reportTitleStruct.getmTitleChildren()[i].getmTitleName())) {
                        //	frozen part
                        this.mFrozenTITLES.add(reportTitleStruct.getmTitleChildren()[i]);
                        if (mFrozenTITLES.get(m).getmTitleChildren() == null) {
                            mFrozenTITLES.get(m).setmSaturability(0);
                        } else {
                            mFrozenTITLES.get(m).setmSaturability(mFrozenTITLES.get(m).getmTitleChildren().length);
                        }
                        leftViewWidth = (int) (leftViewWidth + mFrozenTITLES.get(m).getmTitleContainerWidth());

                        for (int j = 0; j < mFrozenTITLES.get(m).getmSaturability(); j++) {
                            this.frozenTitlesChildren.add(mFrozenTITLES.get(m).getmTitleChildren()[j]);
                        }
                        m = m + 1;
                    } else {
                        //	variational part
                        this.mVariationalTITLES.add(reportTitleStruct.getmTitleChildren()[i]);
                        if (mVariationalTITLES.get(n).getmTitleChildren() == null) {
                            mVariationalTITLES.get(n).setmSaturability(0);
                        } else {
                            mVariationalTITLES.get(n).setmSaturability(mVariationalTITLES.get(n).getmTitleChildren().length);
                        }

                        for (int j = 0; j < mVariationalTITLES.get(n).getmSaturability(); j++) {
                            this.variationalTitlesChildren.add(mVariationalTITLES.get(n).getmTitleChildren()[j]);
                        }
                        n = n + 1;
                    }
                }
            }
        }

        mFrozenTITLES.trimToSize();
        frozenTitlesChildren.trimToSize();
        mVariationalTITLES.trimToSize();
        variationalTitlesChildren.trimToSize();

        mFrozenColumns = getFrozenColumns();
        headerDepth = getHeaderDepth();
        initLastLevelFrozenTitles();
        initLastLevelVariationalTitles();
        idsCount = getIdsCount();
    }

    /**
     * get IdsCount
     *
     * @return
     */
    public int getIdsCount() {

        if (headerDepth == 1) {
            idsCount = mFrozenTITLES.size() + mVariationalTITLES.size();
        } else if (headerDepth == 2) {
            idsCount = frozenTitlesChildren.size() + variationalTitlesChildren.size();
        }

        return idsCount;
    }

    /**
     * initialize Last Level Frozen Titles
     */
    public void initLastLevelFrozenTitles() {

        if (frozenTitlesChildren != null && frozenTitlesChildren.size() > 0) {
            lastLevelFrozenTitles = frozenTitlesChildren;
        } else {
            lastLevelFrozenTitles = mFrozenTITLES;
        }
        lastLevelFrozenTitles.trimToSize();
    }

    /**
     * initialize Last Level Variational Titles
     */
    public void initLastLevelVariationalTitles() {
        if (variationalTitlesChildren != null && variationalTitlesChildren.size() > 0) {
            lastLevelVariationalTitles = variationalTitlesChildren;
        } else {
            lastLevelVariationalTitles = mVariationalTITLES;
        }
        lastLevelVariationalTitles.trimToSize();
    }

    /**
     * get Frozen Columns count
     *
     * @return
     */
    public int getFrozenColumns() {

        if (frozenTitlesChildren != null && frozenTitlesChildren.size() > 0) {
            mFrozenColumns = frozenTitlesChildren.size();
        } else {
            mFrozenColumns = mFrozenTITLES.size();
        }

        return mFrozenColumns;
    }

    /**
     * get header depth
     * if there is only one row titles, then header depth is 1. This means header depth value is rows count of titles.
     * default value is 1 or 2
     *
     * @return
     */
    public int getHeaderDepth() {

        if (frozenTitlesChildren != null && frozenTitlesChildren.size() > 0) {
            return 2;
        }

        return 1;
    }


    /**
     * get Blank Data
     *
     * @param array
     * @return
     */
//    public List<HashMap<String, Object>> getBlankData(ArrayList<ReportTitleStruct> array) {
//        List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
//        HashMap<String, String> dataItem = null;
//
//        //	value given
//        for (int i = 0, frozenContentRowsCount = requestRows; i <= frozenContentRowsCount - 1; i++) {
//            dataItem = new HashMap<String, String>();
//            for (int j = 0; j < array.size(); j++) {
//                dataItem.put(array.get(j).getmTitle(), null);
//            }
//            data.add(dataItem);
//        }
//
//        return data;
//    }

    /**
     * get left frozen content
     *
     * @return
     */
    public List<HashMap<String, String>> getFrozenData() {
        HashMap<String, String> leftFrozenDataItem = null;                                            //	row data

        //	value given
        for (int i = 0; i <= addRows - 1; i++) {
            //	i is current row
            leftFrozenDataItem = new HashMap<>();
            int size = lastLevelFrozenTitles.size();
            for (int j = 0; j < size; j++) {
                String key = lastLevelFrozenTitles.get(j).getmTitleName();
                if (key != null) {
                    if (tableData.get(key) != null) {
                        if (tableData.get(key).get(i) != null) {
                            leftFrozenDataItem.put(
                                    key,
                                    tableData.get(key).get(i) + blankValue);
                        }
                    }
                }
            }
            recordLeftFrozenData.add(leftFrozenDataItem);
        }
        recordLeftFrozenData.trimToSize();

        return recordLeftFrozenData;
    }

    /**
     * get right variational content
     *
     * @return
     */
    public List<HashMap<String, Object>> getData() {

        HashMap<String, Object> rightVariationalDataItem = null;
        Log.i(TAG, "getData" + "{addrows=" + addRows + "size=" + lastLevelVariationalTitles.size() + "");
        //	value given
        for (int i = 0; i <= addRows - 1; i++) {
            //	i is current row
            rightVariationalDataItem = new HashMap<>();

            for (int j = 0; j < lastLevelVariationalTitles.size(); j++) {
                Log.i(TAG, "getData" + "{i=" + i + "j=" + j + "");
                if (tableData.get(lastLevelVariationalTitles.get(j).getmTitleName()) != null && tableData.get(lastLevelVariationalTitles.get(j).getmTitleName()).size() > i) {
                    rightVariationalDataItem.put(
                            lastLevelVariationalTitles.get(j).getmTitleName(),
                            tableData.get(lastLevelVariationalTitles.get(j).getmTitleName()).get(i));
                }
            }
            recordRightVariationalData.add(rightVariationalDataItem);
        }
        recordRightVariationalData.trimToSize();

        return recordRightVariationalData;
    }

    private void onLoad() {
        if (mGridCtrl != null) {
            mGridCtrl.stopLoadMore();
        }
    }

    /**
     * clear data to start refresh
     */
    private void startRefresh() {

        if (mGridCtrl != null) {
            mGridCtrl.SetListVisible(false);
        }

        recordLeftFrozenData.clear();
        recordRightVariationalData.clear();
        temporaryData.clear();
        rightBodyData.clear();
        leftBodyData.clear();
        tableData.clear();

        lastRowsCount = 0;
        addRows = 0;
        currentRowsCount = 0;
        requestPageIndex = 1;
    }

    @Override
    public void onRefresh() {

        startRefresh();
        produceTableData();
//        requestTableData();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                onLoad();
            }
        }, 1000);
    }

    @Override
    public void onLoadMore() {
        eQTableOnListener.pullFreshPage(reportLayerName, requestPageIndex);
        lastRowsCount = currentRowsCount;
    }

    /**
     * 画复杂表头，传递复杂表头的数据
     *
     * @param reportTitleStruct
     */
    public void setReportTitleStruct(ReportTitleStruct reportTitleStruct) {
        this.reportTitleStruct = reportTitleStruct;
//        mGridCtrl = (EQGridCtrl) LayoutInflater.from(context).inflate(R.layout.gridctrl_layout, null);
//        mGridCtrl.mHeight = (int) reportTitleStruct.getmTitleContainerHeight();//464.5dip
        mGridCtrl.mHeight = getResources().getDimensionPixelOffset(R.dimen.table_height_portrait);

        if (mGridCtrl != null && reportTitleStruct != null) {
            mGridCtrl.setGridDataSource(this);
//            mGridCtrl.setX(reportTitleStruct.getmTitleContainerLeft());
//            mGridCtrl.setY(reportTitleStruct.getmTitleContainerTop());
//			mGridCtrl.setLayoutParams(new LayoutParams((int)reportTitleStruct.getmTitleContainerWidth(), (int)reportTitleStruct.getmTitleContainerHeight())) ;
//            rootView.addView(mGridCtrl);

            EQGridCtrl.EQGridHeader virfixHeader = mGridCtrl.CreateEQGridHeader();
            if (virfixHeader.getSubHeaders() != null) {
                virfixHeader.getSubHeaders().clear();
            }
            virfixHeader.SetVirtual(true);
            EQGridCtrl.EQGridHeader virotherHeader = mGridCtrl.CreateEQGridHeader();
            if (virotherHeader.getSubHeaders() != null) {
                virotherHeader.getSubHeaders().clear();
            }
            virotherHeader.SetVirtual(true);
            for (int i = 0; i < (reportTitleStruct.getmTitleChildren()).length; i++) {
                ReportTitleStruct child = reportTitleStruct.getmTitleChildren()[i];
                if (child != null) {
                    EQGridCtrl.EQGridHeader header = mGridCtrl.CreateEQGridHeader();
                    header.SetName(child.getmTitle());
                    header.setAlignment(child.getmAlignment());
                    header.SetId(child.getmTitleName());
                    if ((child.getmTitleChildren() != null) && (child.getmTitleChildren()).length > 0) {
                        for (int j = 0; j < (child.getmTitleChildren()).length; j++) {
                            ReportTitleStruct child2 = child.getmTitleChildren()[j];
                            if (child2 != null) {
                                EQGridCtrl.EQGridHeader header2 = mGridCtrl.CreateEQGridHeader();
                                String name = child2.getmTitle();
                                header2.SetName(name);
                                header2.SetId(child2.getmTitleName());
                                header2.SetWidth((int) child2.getmTitleContainerWidth());
                                header2.setAlignment(child2.getmAlignment());
                                header.AddSubHeader(header2);
                            }
                        }
                        header.SetWidth(0);
                    } else {
//                        header.SetWidth((int) child.getmTitleContainerWidth());
//                        header.SetWidth(120);
                        header.SetWidth(getResources().getDimensionPixelSize(R.dimen.tablecontent_unit_height));
                    }

                    if ("0".equals(child.getmTitleName())) {
                        virfixHeader.AddSubHeader(header);
                    } else {
                        virotherHeader.AddSubHeader(header);
                    }
                }
            }

            mGridCtrl.setFixHeader(virfixHeader);
            mGridCtrl.setOtherHeader(virotherHeader);
            mGridCtrl.initSubView();
        }

        mFrozenTITLES.clear();
        frozenTitlesChildren.clear();
        mVariationalTITLES.clear();
        variationalTitlesChildren.clear();
        lastLevelFrozenTitles.clear();
        lastLevelVariationalTitles.clear();
        if (fixdata != null) {
            fixdata.clear();
        }
        if (otherdata != null) {
            otherdata.clear();
        }

        initTitlesContent(this.reportTitleStruct);

        //**	draw table header here	**//
        drawTableHeaderWithoutContent();
        if (mGridCtrl != null) {
//            fixdata = getBlankData(lastLevelFrozenTitles);
//            otherdata = getBlankData(lastLevelVariationalTitles);
            mGridCtrl.notifyDataSetChanged();
        }
    }

    public void notifiedPageFillView(List<HotelstateBean.HeadBean> head, List<List<HotelstateBean.BodyBean>> body, List<HotelstateBean.LeftBean> left) {
        this.head = head;
        this.bodyData = body;
        this.left = left;

        if (mGridCtrl != null) {
            mGridCtrl.stopLoadMore();
        }
        if (requestPageIndex == 1) {
            //	load 15 rows data once
            prepareData();

            if (tableData != null) {
                refreshTable();
                if (rootView != null) {
                    if (currentRowsCount <= displayRows) {
                        mGridCtrl.hideEndReminder();
                    }
                    rootView.requestLayout();
                }

                selectFirstRow();
            }

            if (mGridCtrl != null) {
                mGridCtrl.SetListVisible(true);
            }

            requestPageIndex++;

        } else if (requestPageIndex >= 2) {
            //	load more 15 rows data
            lastRowsCount = currentRowsCount;

            prepareData();

            if (tableData != null) {

                addDataContent(context);

                if (mGridCtrl == null) {
                    Handler handler = new Handler();
                    Runnable runnable = new Runnable() {

                        @Override
                        public void run() {
//                            rootView.postInvalidate();
                            rootView.requestLayout();
                        }
                    };
                    handler.postDelayed(runnable, 500);
                }

                moveToNewPosition();
                mGridCtrl.notifyDataSetChanged();
                lastRowsCount = currentRowsCount;
            }
            requestPageIndex++;
        }
        if (mGridCtrl != null) {
            if (eQTableOnListener != null && mGridCtrl.listView != null && reportLayerName != null) {
                mGridCtrl.listView.eQTableOnListener = eQTableOnListener;
                mGridCtrl.listView.reportLayerName = reportLayerName;
            }
        }

        finishData();
    }

    /**
     * clear unused data
     */
    private void finishData() {

        if (tableData != null && tableData.size() > 0) {
            tableData.clear();
        }
    }

    /**
     * after pull up, move to new first visible position
     */
    private void moveToNewPosition() {
        if (mGridCtrl != null) {
            mGridCtrl.moveToNewPosition(lastRowsCount - 1);
            //**	select first row	**//
            eQTableOnListener.onClickTableContentListener(reportLayerName, lastRowsCount - 1);
        }
    }

    /**
     * select first row in first time
     */
    private void selectFirstRow() {

        if (lastRowsCount == 0) {
            //**	select first row	**//
            eQTableOnListener.onClickTableContentListener(reportLayerName, lastRowsCount);
            if (mGridCtrl != null) {
                mGridCtrl.onItemClick(mGridCtrl.listView, null, 0, 0);
            }
        }
    }

    /**
     * prepare Data
     */
    private void prepareData() {

//        requestTableData();
        produceTableData();
    }

    /**
     * draw Table Header
     */
    private void drawTableHeaderWithoutContent() {

        initTableWithoutContent(context);
    }

    /**
     * dataType: "dt_string", "dt_thscode", "dt_integer", "dt_date", "dt_memo", "dt_double"
     * dataFmt: "%d", "%.02f", "%.0xf"
     * get value showed in format style
     *
     * @return
     */
    private String getShowValue(String datatype, String datafmt, String value) {
        String showValue = "--";

        if ((value != null && !"--".equals(value)) && "dt_integer".equals(datatype)) {
            showValue = (int) (Double.valueOf(value) + 0.5) + "";
            return showValue;
        }

        if ((value == null || "--".equals(value)) && "dt_integer".equals(datatype)) {
            showValue = 0 + "";
            return showValue;
        }

        if (value == null || value.equals(showValue)) {
            return showValue;
        } else if ("dt_double".equals(datatype) && value != null) {
            showValue = String.format(datafmt, Double.valueOf(value));
            return showValue;
        } else {
            showValue = value;
        }

        return showValue;
    }

    @Override
    public int getCount() {
        if (fixdata != null && otherdata != null) {
            return fixdata.size();
        }
        return 0;
    }

    @Override
    public String getString(int nRow, int Col) {
        int lastLevelFrozenTitlesSize = 0;
        int lastLevelVariationalTitlesSize = 0;
        if (lastLevelFrozenTitles != null && lastLevelVariationalTitles != null) {
            lastLevelFrozenTitlesSize = lastLevelFrozenTitles.size();
            lastLevelVariationalTitlesSize = lastLevelVariationalTitles.size();
            if (lastLevelFrozenTitlesSize > 0 && lastLevelVariationalTitlesSize > 0
                    && fixdata != null && otherdata != null) {
                ReportTitleStruct titleStruct = null;
                if (Col >= 0 && Col < lastLevelFrozenTitlesSize) {
                    titleStruct = lastLevelFrozenTitles.get(Col);
                    if (nRow >= fixdata.size()) {
                        if (!dialogShow) {
                            mGridCtrl.setNoDataReminder();
                            dialogShow = true;
                        }
                    } else if (fixdata.get(nRow) != null && titleStruct != null
                            && titleStruct.getmTitleName() != null) {
                        String valueToShow = fixdata.get(nRow).get(titleStruct.getmTitleName());
                        String datatype = titleStruct.getmDataType();
                        String datafmt = titleStruct.getmDataFormat();

                        return getShowValue(datatype, datafmt, valueToShow);
                    }

                } else if (Col >= lastLevelFrozenTitlesSize && Col < (lastLevelVariationalTitlesSize + lastLevelFrozenTitlesSize)) {
                    titleStruct = lastLevelVariationalTitles.get(Col - lastLevelFrozenTitlesSize);
                    if (nRow >= otherdata.size()) {
                        if (!dialogShow) {
                            mGridCtrl.setNoDataReminder();
                            dialogShow = true;
                        }
                    } else if (otherdata.get(nRow) != null && titleStruct != null
                            && titleStruct.getmTitleName() != null) {
                        Object bodyBean = otherdata.get(nRow).get(titleStruct.getmTitleName());
                        String valueToShow = "";
                        if (bodyBean instanceof HotelstateBean.BodyBean) {
                            valueToShow = ((HotelstateBean.BodyBean) bodyBean).getUserName();
                        }

                        String datatype = titleStruct.getmDataType();
                        String datafmt = titleStruct.getmDataFormat();

                        return getShowValue(datatype, datafmt, valueToShow);
                    }
                }
            }
        }

        return null;
    }

    @Override
    public String getDataType(int nRow, int Col) {

        if (Col >= 0 && Col < lastLevelFrozenTitles.size()) {
            String dataType = lastLevelFrozenTitles.get(Col).getmDataType();
            return dataType;
        } else if (Col >= lastLevelFrozenTitles.size() && Col < (lastLevelVariationalTitles.size() + lastLevelFrozenTitles.size())) {
            String dataType = lastLevelVariationalTitles.get(Col - lastLevelFrozenTitles.size()).getmDataType();
            return dataType;
        }
        return null;
    }

    @Override
    public String getDataFormat(int nRow, int Col) {

        if (Col >= 0 && Col < lastLevelFrozenTitles.size()) {
            String datafmt = lastLevelFrozenTitles.get(Col).getmDataFormat();
            return datafmt;
        } else if (Col >= lastLevelFrozenTitles.size() && Col < (lastLevelVariationalTitles.size() + lastLevelFrozenTitles.size())) {
            String datafmt = lastLevelVariationalTitles.get(Col - lastLevelFrozenTitles.size()).getmDataFormat();
            return datafmt;
        }
        return null;
    }

    @Override
    public HotelstateBean.BodyBean getBodyBean(int nRow, int Col) {
        int size = lastLevelFrozenTitles.size();
        if (nRow < otherdata.size() && Col - size < lastLevelVariationalTitles.size()) {
            Object bodyBean = otherdata.get(nRow).get(lastLevelVariationalTitles.get(Col - size).getmTitleName());
            if (bodyBean instanceof HotelstateBean.BodyBean) {
                return (HotelstateBean.BodyBean) bodyBean;
            }
        }
        return null;
    }

    @Override
    public String getOrderId(int nRow, int Col) {
        String orderId = "-1";
        HotelstateBean.BodyBean bodyBean = getBodyBean(nRow, Col);
        if (bodyBean != null) {
            orderId = bodyBean.getOrderId();
        }

        return orderId;
    }

    @Override
    public int getOrderStatus(int nRow, int Col) {
        int orderStatus = -1;
        HotelstateBean.BodyBean bodyBean = getBodyBean(nRow, Col);
        if (bodyBean != null) {
            orderStatus = bodyBean.getOrderStatus();
        }

        return orderStatus;
    }

    @Override
    public String getUserName(int nRow, int Col) {
        String userName = "";
        HotelstateBean.BodyBean bodyBean = getBodyBean(nRow, Col);
        if (bodyBean != null) {
            userName = bodyBean.getUserName();
        }

        return userName;
    }

    @Override
    public String getSkuId(int nRow, int Col) {
        String skuId = "-1";
        HotelstateBean.BodyBean bodyBean = getBodyBean(nRow, Col);
        if (bodyBean != null) {
            skuId = bodyBean.getSkuId();
        }

        return skuId;
    }

    @Override
    public String getSkuName(int nRow, int Col) {
        String skuName = "";
        HotelstateBean.BodyBean bodyBean = getBodyBean(nRow, Col);
        if (bodyBean != null) {
            skuName = bodyBean.getSkuName();
        }

        return skuName;
    }

    @Override
    public String getDate(int nRow, int Col) {
        String date = "";
        HotelstateBean.BodyBean bodyBean = getBodyBean(nRow, Col);
        if (bodyBean != null) {
            date = bodyBean.getDate();
        }

        return date;
    }

    @Override
    public void notifyHeaderTextViewCreate(TextView v) {
    }

    @Override
    public void notifyLoadMore() {
        onLoadMore();
    }

    @Override
    public void onClickTableContentListener(int nRow) {
        if (eQTableOnListener != null) {
            eQTableOnListener.onClickTableContentListener(reportLayerName, nRow);
        }
    }
}
